package br.com.senac.controle;

import br.com.ecommercer.bean.Usuario;
import br.com.ecommercer.dao.UsuarioDao;
import br.com.ecommercer.dao.UsuarioDaoImp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(name = "UsuarioServlet", urlPatterns = {"/UsuarioServlet"})
public class UsuarioServlet extends HttpServlet {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private RequestDispatcher rd;
    private UsuarioDao usuarioDao;
    private Usuario usuario;

    protected void processRequest() throws ServletException, IOException {
        String cmd = request.getParameter("cmd");
        switch (cmd) {
            case "logar":
                logar();
                break;
            case "sair":
                logof();
                break;
        }
        rd.forward(request, response);
    }

    private void logar() {
        usuarioDao = new UsuarioDaoImp();
        try {
            String login = request.getParameter("login");
            String senha = request.getParameter("senha");
            Boolean tipoAcesso = (Boolean.parseBoolean(request.getParameter("tipoAcesso")));
            usuario = usuarioDao.logar(login, senha, tipoAcesso);
            if (usuario.isLogado()) {
                HttpSession session = request.getSession(true);
                session.setAttribute("usuario", usuario);
                rd = request.getRequestDispatcher("index.jsp");
            } else {
                request.setAttribute("mens", "Login ou Senha incorretos!");
                rd = request.getRequestDispatcher("logar.jsp");
            }
        } catch (Exception e) {
            request.setAttribute("mens", "Erro ao logar!");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.request = request;
        this.response = response;
        processRequest();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.request = request;
        this.response = response;
        processRequest();
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void logof() {
        HttpSession session = request.getSession(true);
        session.removeAttribute("usuario");
        rd = request.getRequestDispatcher("logar.jsp");
    }
}
